package com.sunxd.disruptor.test;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.sunxd.disruptor.event.LongEvent;
import com.sunxd.disruptor.factory.LongEventFactory;
import com.sunxd.disruptor.handler.LongEventHandler;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *
 * 基础的发布
 * @author: 作者名称
 * @date: 2021-09-24 15:57
 **/
public class Run1 {
    public static void main(String[] args) {
        LongEventFactory longEventFactory = new LongEventFactory();
        int bufferSize = 8;
        Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(longEventFactory,bufferSize, Executors.defaultThreadFactory());
        disruptor.handleEventsWith(new LongEventHandler());
        disruptor.start();

        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread( () ->{
                publishInfo(ringBuffer, finalI);
            }).start();

        }

        publishInfo(ringBuffer,999);


    }

    public static void  publishInfo(RingBuffer<LongEvent> ringBuffer,int i){
        long sequence = ringBuffer.next();
        Random random = new Random();
        try {
            // 测试阻塞
            TimeUnit.SECONDS.sleep(5+random.nextInt(1));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            //用上面的索引取出一个空的事件用于填充
            LongEvent event = ringBuffer.get(sequence);// for the sequence
            event.setValue(i);
        } finally {
            //发布事件
            ringBuffer.publish(sequence);
        }
    }
}
